using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Core.Foundation.Standards;

namespace Core.Foundation.Features.Application_Configuration
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("5970f62e-430e-47cc-a7a7-5b91d9ff3a2e")]
    public class Application_ConfigurationEventReceiver : SPFeatureReceiver
    {


        /// <summary>
        /// FeatureActivated
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                Logging.LogToULS("Feature Activation Started for Application Configuration", FoundationConstants.featuresLog);
                // reset the static thredsafe allow updates
                CoreHelper.ResetWebSafeDictionaries();

                try { DirectEventLog.EnsureEventLogSource(); }
                catch { }

                FoundationAppConfig.LoggingCategories logConfig = new FoundationAppConfig.LoggingCategories();
                LogHelper.SyncConfiguration(logConfig, FoundationAppConfig.Module);
                Logging.LogToULS("Logging Categories Installed", FoundationConstants.featuresLog);


                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    Logging.LogToULS("Create Site Columns, Content Type, and List for AppConfig", FoundationConstants.featuresLog);
                    SPWeb web = CoreHelper.GetCoreWeb();                
                    // create content type for AppConfig
                    CreateAppConfigContentType(web);
                    // create and populate list            
                    CreateAppConfigList(web);
                    web.Dispose();
                });

                Logging.LogToULS("AppConfig List routines complete", FoundationConstants.featuresLog);

                Logging.LogToULS("Add Versioning", FoundationConstants.featuresLog);
                AppConfig.Helper.AddSolutionVersion(FoundationAppConfig.Module);
                    
                AppConfig.Helper.AppConfigEntries(new FoundationAppConfig(), CoreHelper.Versioning.GetSolutionVersion());
                Logging.LogToULS("Application Configuration Items Added", FoundationConstants.featuresLog);

                Logging.LogToULS("Feature Activation Complete for Application Configuration", FoundationConstants.featuresLog);
            }
            catch (Exception ex)
            {
                Logging.LogError(ex, FoundationConstants.featuresLog);
                throw;
            }
        }


        /// <summary>
        /// FeatureDeactivating
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            Logging.LogToULS("Feature Deactivating Started for Application Configuration", FoundationConstants.featuresLog);
            Standards.Logging.LogToULS("Logging Categories Being Removed for Foundation", FoundationAppConfig.LoggingCategories.Core);
            LogHelper.RemoveConfiguration(FoundationAppConfig.Module);
            Logging.LogToULS("Feature Deactivation Finished for Application Configuration", FoundationConstants.featuresLog);

        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}



        private void CreateAppConfigList(SPWeb web)
        {
            Guid listGuid;
            Logging.LogToULS("Creating AppConfig List", FoundationConstants.featuresLog);
            try
            {
                Guid webSafe = CoreHelper.AllowUnSafeUpdates(ref web);
                listGuid = web.Lists.Add(FoundationConstants.AppConfigListName, "", SPListTemplateType.GenericList);
                SPList AppConfigList = web.Lists[listGuid];
                AppConfigList.Title = FoundationConstants.AppConfigListName;
                AppConfigList.OnQuickLaunch = false;
                AppConfigList.ContentTypesEnabled = true;
                AppConfigList.ContentTypes.Add(web.Site.RootWeb.ContentTypes[FoundationConstants.AppConfigContentTypeName]);

                //remove the default Item content type
                AppConfigList.ContentTypes.Delete(AppConfigList.ContentTypes["Item"].Id);

                //Make sure changes are committed to the list
                AppConfigList.Update();

                SPView defaultView = AppConfigList.DefaultView;
                defaultView.ViewFields.Add("AppConfig Module");
                defaultView.ViewFields.Add("AppConfig Group");
                defaultView.ViewFields.Add("AppConfig Key");
                defaultView.ViewFields.Add("AppConfig Value");
                defaultView.ViewFields.Add("AppConfig Active");
                defaultView.ViewFields.Add("AppConfig Encrypted");
                defaultView.ViewFields.Add("AppConfig Version");
                defaultView.ViewFields.Add("Modified");
                defaultView.Update();
                AppConfigList.Update();

                CoreHelper.AllowUnSafeUpdates(ref web, webSafe);
                Logging.LogToULS("Created AppConfig List", FoundationConstants.featuresLog);
            }
            catch (Exception ex)
            {
                Logging.LogError(ex, FoundationConstants.featuresLog);
            }


        }

        private void CreateAppConfigContentType(SPWeb web)
        {

            #region Variables & Constants
            string FieldName = string.Empty;
            string FieldDisplayName = string.Empty;

            #endregion

            #region Site column: Module
            if (web.AvailableFields.Contains(FoundationColumnID.Module) == false)
            {
                FieldName = "AppConfigModule";
                FieldDisplayName = "AppConfig Module";
                string OnSiteCreateXML = CoreHelper.GetFieldXml(FoundationColumnID.Module, FieldName, FieldDisplayName, FoundationConstants.SiteColumnGroup, true, true, false, FoundationEnums.FieldTypes.Text, FoundationEnums.Format.NoFormat);
                CoreHelper.CreateSiteColumn(web, FoundationColumnID.Module, OnSiteCreateXML);
                CoreHelper.UpdateColumnForDescription(web, FoundationColumnID.Module, FoundationConstants.FieldDesc);
            }
            

            #endregion

            #region Site column: Group
            if (web.AvailableFields.Contains(FoundationColumnID.Group) == false)
            {
                FieldName = "AppConfigGroup";
                FieldDisplayName = "AppConfig Group";
                string OnSiteActiveXML = CoreHelper.GetFieldXml(FoundationColumnID.Group, FieldName, FieldDisplayName, FoundationConstants.SiteColumnGroup, true, true, false, FoundationEnums.FieldTypes.Text, FoundationEnums.Format.NoFormat);
                CoreHelper.CreateSiteColumn(web, FoundationColumnID.Group, OnSiteActiveXML);
                CoreHelper.UpdateColumnForDescription(web, FoundationColumnID.Group, FoundationConstants.FieldDesc);
            }
            #endregion

            #region Site column: Key
            if (web.AvailableFields.Contains(FoundationColumnID.Key) == false)
            {
                FieldName = "AppConfigKey";
                FieldDisplayName = "AppConfig Key";
                string OnSiteInactiveXML = CoreHelper.GetFieldXml(FoundationColumnID.Key, FieldName, FieldDisplayName, FoundationConstants.SiteColumnGroup, true, true, false, FoundationEnums.FieldTypes.Text, FoundationEnums.Format.NoFormat);
                CoreHelper.CreateSiteColumn(web, FoundationColumnID.Key, OnSiteInactiveXML);
                CoreHelper.UpdateColumnForDescription(web, FoundationColumnID.Key, FoundationConstants.FieldDesc);
            }
            #endregion

            #region Site column: Value
            if (web.AvailableFields.Contains(FoundationColumnID.Value) == false)
            {
                FieldName = "AppConfigValue";
                FieldDisplayName = "AppConfig Value";
                string OnSiteArchiveXML = CoreHelper.GetFieldXml(FoundationColumnID.Value, FieldName, FieldDisplayName, FoundationConstants.SiteColumnGroup, true, true, false, FoundationEnums.FieldTypes.Text, FoundationEnums.Format.NoFormat);
                CoreHelper.CreateSiteColumn(web, FoundationColumnID.Value, OnSiteArchiveXML);
                CoreHelper.UpdateColumnForDescription(web, FoundationColumnID.Value, FoundationConstants.FieldDesc);
            }
            #endregion

            #region Site column: Active
            if (web.AvailableFields.Contains(FoundationColumnID.Active) == false)
            {
                FieldName = "AppConfigActive";
                FieldDisplayName = "AppConfig Active";
                string OnSiteArchiveXML = CoreHelper.GetFieldXml(FoundationColumnID.Active, FieldName, FieldDisplayName, FoundationConstants.SiteColumnGroup, true, true, false, FoundationEnums.FieldTypes.Boolean, FoundationEnums.Format.NoFormat);
                CoreHelper.CreateSiteColumn(web, FoundationColumnID.Active, OnSiteArchiveXML);
                CoreHelper.UpdateColumnForDescription(web, FoundationColumnID.Active, FoundationConstants.FieldDesc);
            }
            #endregion

            #region Site column: Version
            if (web.AvailableFields.Contains(FoundationColumnID.Version) == false)
            {
                FieldName = "AppConfigVersion";
                FieldDisplayName = "AppConfig Version";
                string OnSiteArchiveXML = CoreHelper.GetFieldXml(FoundationColumnID.Version, FieldName, FieldDisplayName, FoundationConstants.SiteColumnGroup, true, true, false, FoundationEnums.FieldTypes.Text, FoundationEnums.Format.NoFormat);
                CoreHelper.CreateSiteColumn(web, FoundationColumnID.Version, OnSiteArchiveXML);
                CoreHelper.UpdateColumnForDescription(web, FoundationColumnID.Version, FoundationConstants.FieldDesc);
            }
            #endregion

            #region Site column: Active
            if (web.AvailableFields.Contains(FoundationColumnID.Encrypted) == false)
            {
                FieldName = "AppConfigEncrypted";
                FieldDisplayName = "AppConfig Encrypted";
                string OnSiteArchiveXML = CoreHelper.GetFieldXml(FoundationColumnID.Encrypted, FieldName, FieldDisplayName, FoundationConstants.SiteColumnGroup, true, true, false, FoundationEnums.FieldTypes.Boolean, FoundationEnums.Format.NoFormat);
                CoreHelper.CreateSiteColumn(web, FoundationColumnID.Encrypted, OnSiteArchiveXML);
                CoreHelper.UpdateColumnForDescription(web, FoundationColumnID.Encrypted, FoundationConstants.FieldDesc);
            }
            #endregion

            #region Content type: AppConfig

            SPContentTypeId AppConfigId = new SPContentTypeId(FoundationContentTypeID.AppConfig.ToString());
            SPContentType AppConfig = web.ContentTypes[AppConfigId];

            try
            {


                if (AppConfig == null)
                {
                    AppConfig = new SPContentType(AppConfigId, web.ContentTypes, FoundationConstants.AppConfigContentTypeName);
                    AppConfig.Group = FoundationConstants.ContentTypeGroup;
                    AppConfig.Description = FoundationConstants.FieldDesc;
                    web.ContentTypes.Add(AppConfig);
                    web.Update();
                }

            }
            catch (Exception ex)
            {
                Logging.LogError(ex, FoundationConstants.featuresLog);
            }



            #region Add Module to ContentType

            CoreHelper.AddColumnToContentType(FoundationColumnID.Module, web, AppConfig);

            #endregion

            #region Add Group to ContentType

            CoreHelper.AddColumnToContentType(FoundationColumnID.Group, web, AppConfig);

            #endregion

            #region Add Key to ContentType

            CoreHelper.AddColumnToContentType(FoundationColumnID.Key, web, AppConfig);

            #endregion

            #region Add Value to ContentType

            CoreHelper.AddColumnToContentType(FoundationColumnID.Value, web, AppConfig);

            #endregion

            #region Add Active to ContentType

            CoreHelper.AddColumnToContentType(FoundationColumnID.Active, web, AppConfig);

            #endregion

            #region Add Encrypted to ContentType

            CoreHelper.AddColumnToContentType(FoundationColumnID.Encrypted, web, AppConfig);

            #endregion

            #region Add Version to ContentType

            CoreHelper.AddColumnToContentType(FoundationColumnID.Version, web, AppConfig);

            #endregion

            #endregion
        }


 
    }
}
